package com.ocom.xcxapi.controller;

import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.HttpUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.redis.util.RedisUtil;
import com.ocom.xcxapi.service.TcpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

//@PreAuthorize("hasRole('ROLE_XCX')")
@RestController
public class WeChatController {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取小程序token
     */
    @PostMapping(WxServiceUrl.Url_getXcxAccessToken)
    public Result getXcxAccessToken(@RequestParam("comId") Long comId, @RequestParam("appid")String appid, @RequestParam("secret")String secret) {
        if (comId == null || StringUtils.isBlank(appid) || StringUtils.isBlank(secret)) {
            return ResultUtil.error(ResultEnum.Err_1001);
        }
        Object er = redisUtil.get("XcxAccessToken:comId:appid:secret" + comId + appid + secret);
        if (er != null) {
            String token = (String) er;
            return ResultUtil.success(token);
        }

        String wxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;

        Map<String, Object> map = HttpUtils.doGet(wxTokenUrl);

        String token = (String) map.get("access_token");
        redisUtil.set("XcxAccessToken:comId:appid:secret" + comId + appid + secret, token, 5400l);
        return ResultUtil.success(token);
    }
}
